package com.evaluation_system.interceptor;

import com.evaluation_system.pojo.Result.Result;
import com.evaluation_system.service.NonceService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class NonceInterceptor implements HandlerInterceptor {

    @Autowired
    NonceService nonceService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String nonce = request.getHeader("X-Nonce");

        if (nonce == null || nonceService.isUsed(nonce)) {
            // 构建标准错误响应
            Result<Object> errorResult = Result.error("Replay attack detected");

            // 转换为 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(errorResult);

            // 设置响应内容
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);
            return false;
        }

        nonceService.markUsed(nonce);
        return true;
    }
}
